extends Resource
class_name Inventory

signal inventory_changed

@export var slots: Array[InventorySlot] = []
var size = 25  # 修改为25个格子 (5行5列)

func _init():
	print("Inventory initialized")  # 调试信息
	for i in size:
		slots.append(InventorySlot.new())

# 添加物品，返回是否成功
func add_item(item: Item, amount: int = 1) -> bool:
	print("Adding item to inventory: ", item.name, " amount: ", amount)  # 调试信息
	# 先尝试堆叠
	if item.stackable:
		for slot in slots:
			if slot.item and slot.item.id == item.id and slot.amount < item.max_stack:
				var space = item.max_stack - slot.amount
				var add_amount = min(space, amount)
				slot.amount += add_amount
				amount -= add_amount
				if amount <= 0:
					inventory_changed.emit()
					print("Item stacked successfully")  # 调试信息
					return true
	
	# 找空位放剩余的
	for slot in slots:
		if not slot.item:
			slot.item = item
			slot.amount = min(amount, item.max_stack)
			amount -= slot.amount
			if amount <= 0:
				inventory_changed.emit()
				print("Item added to empty slot")  # 调试信息
				return true
	
	print("Failed to add item: no space")  # 调试信息
	return false

# 移除物品
func remove_item(item: Item, amount: int = 1) -> bool:
	var remaining = amount
	
	for slot in slots:
		if slot.item and slot.item.id == item.id:
			if slot.amount >= remaining:
				slot.amount -= remaining
				if slot.amount == 0:
					slot.item = null
				inventory_changed.emit()
				return true
			else:
				remaining -= slot.amount
				slot.amount = 0
				slot.item = null
	
	return false

func has_item(item_name: String) -> bool:
	for slot in slots:
		if slot.item and slot.item.name == item_name:
			return true
	return false 
